package com.chain.BrotherExchange.ui.fragment;

import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;

import com.chain.BrotherExchange.R;
import com.chain.BrotherExchange.data.Resource;
import com.chain.BrotherExchange.data.model.LegalTenderOrderList;
import com.chain.BrotherExchange.event.LegalTenderOrderChangeEvent;
import com.chain.BrotherExchange.event.SubmitAppealSuccessEvent;
import com.chain.BrotherExchange.ui.adapter.LegalTenderOrderListAdapter;
import com.chain.BrotherExchange.ui.core.AbsNetworkStateFragment;
import com.chain.BrotherExchange.ui.dialog.TransactionPasswordDialog;
import com.chain.BrotherExchange.utils.Androids;
import com.chain.BrotherExchange.utils.FirstItemMarginDecoration;
import com.chain.BrotherExchange.viewmodel.OrderViewModel;
import com.chain.BrotherExchange.viewmodel.core.ViewModelProviders;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import org.greenrobot.eventbus.Subscribe;

import butterknife.Bind;

/**
 * 法币订单列表
 */
public class LegalTenderOrderListFragment extends AbsNetworkStateFragment implements OnRefreshLoadmoreListener {

    @Bind(R.id.recycler_view) RecyclerView mRecyclerView;
    @Bind(R.id.smart_refresh_layout) SmartRefreshLayout mSmartRefreshLayout;

    private OrderViewModel mViewModel;
    private LegalTenderOrderListAdapter mLegalTenderOrderListAdapter;

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Override
    protected int getLayoutID() {
        return R.layout.simple_load_refresh_recycler_view;
    }

    @Override
    protected void initActions() {
        mViewModel = ViewModelProviders.of(this).get(OrderViewModel.class);

        // 刷新加载监听
        mSmartRefreshLayout.setOnRefreshLoadmoreListener(this);

        // 订单列表
        mLegalTenderOrderListAdapter = new LegalTenderOrderListAdapter();
        mRecyclerView.setAdapter(mLegalTenderOrderListAdapter);
        mRecyclerView.addItemDecoration(new FirstItemMarginDecoration());
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mLegalTenderOrderListAdapter.setPaymentListener((this::orderPayment));
        mLegalTenderOrderListAdapter.setCancelOrderListener(this::cancelOrder);
        mLegalTenderOrderListAdapter.setOrderReleaseListener(this::orderRelease);
        mLegalTenderOrderListAdapter.setCancelAppealListener(this::cancelAppeal);

        // 请求订单列表
        initLegalTenderOrder();
    }

    private void cancelAppeal(int position, int id) {
        mViewModel.cancelAppeal(id).observe(this, resource -> {
            Androids.makeText(resource.message);
            mLegalTenderOrderListAdapter.getItem(position).setAppeal_states(4);
            mLegalTenderOrderListAdapter.notifyItemChanged(position);
        });
    }

    private void orderRelease(int position, int id) {
        TransactionPasswordDialog.show(getContext(), dialog -> {
            mViewModel.orderRelease(id, dialog.getPassword()).observe(this, resource -> {
                        if (resource.state == Resource.Status.LOADING) {
                            Androids.showProgressMessage(getContext(), R.string.message_release_ing);
                        } else {
                            Androids.dismissProgressMessage();
                            Androids.makeText(resource.message);
                            if (resource.state == Resource.Status.SUCCESS) {
                                dialog.dismiss();
                                mLegalTenderOrderListAdapter.changeOrderState(3, position);
                            }
                        }
                    }
            );
        });
    }

    private void cancelOrder(int position, int id) {
        mViewModel.cancelLegalTenderOrder(id, mLegalTenderOrderListAdapter.getItem(position).getAd_type())
                .observe(this, resource -> {
                    if (resource.state == Resource.Status.LOADING) {
                        Androids.showProgressMessage(getContext(), R.string.message_cancelling_order);
                    } else {
                        Androids.dismissProgressMessage();
                        Androids.makeText(resource.message);
                        if (resource.state == Resource.Status.SUCCESS) {
                            mLegalTenderOrderListAdapter.changeOrderState(4, position);
                        }
                    }
                });
    }

    private void orderPayment(int position, int id) {
        mViewModel.confirmPayment(id).observe(this, resource -> {
            if (resource.state == Resource.Status.LOADING) {
                Androids.showProgressMessage(getContext(), R.string.message_confirm_payment);
            } else {
                Androids.dismissProgressMessage();
                Androids.makeText(resource.message);
                if (resource.state == Resource.Status.SUCCESS) {
                    mLegalTenderOrderListAdapter.changeOrderState(2, position);
                }
            }
        });
    }

    private void initLegalTenderOrder() {
        mViewModel.newLegalTenderOrder().observe(this, resource -> {
            Resource.load(getContext(), resource, this, result -> {
                mLegalTenderOrderListAdapter.setOrder(resource.source);
                mSmartRefreshLayout.finishRefresh();
            });
        });
    }


    @Override
    public void onAnewRequest() {
        initLegalTenderOrder();
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        mViewModel.moreLegalTenderOrder().observe(this, resource -> {
            switch (resource.state) {
                case EMPTY:
                    Androids.makeText(R.string.no_more);
                    break;
                case NOT_NETWORK:
                    Androids.makeText(R.string.network_error);
                    break;
                case ERROR:
                    Androids.makeText(resource.message);
                    break;
                case SUCCESS:
                    mLegalTenderOrderListAdapter.addOrder(resource.source);
                    break;
            }

            mSmartRefreshLayout.finishLoadmore(0);
        });
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        initLegalTenderOrder();
    }

    @Subscribe
    public void legalTenderOrderChangeEvent(LegalTenderOrderChangeEvent event) {
        mLegalTenderOrderListAdapter.changeOrderState(event.state, event.position);
    }

    @Subscribe
    public void submitAppealSuccessEvent(SubmitAppealSuccessEvent event) {
        LegalTenderOrderList.DataBean.ListBean bean = mLegalTenderOrderListAdapter.getItem(event.position);
        bean.setAppeal_states(1);
        bean.setAppeal_id(event.id);
        mLegalTenderOrderListAdapter.notifyItemChanged(event.position);
    }
}
